﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="recPaymentform.aspx.cs" Inherits="SIPO.Web.Forms.Transaction.recPaymentform" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Payment Form</title>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.wrapper.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.inputmask.bundle.min.js") %>" type="text/javascript"></script>

</head>
<style type="text/css">
    .ui-autocomplete
    {
        max-height: 100px;
        overflow-y: auto; /* prevent horizontal scrollbar */
        overflow-x: hidden; /* add padding to account for vertical scrollbar */
        padding-right: 20px;
    }
    .custom-combobox
    {
        position: relative;
        display: inline-block;
    }
    .custom-combobox-toggle
    {
        position: absolute;
        top: 0;
        bottom: 0;
        margin-left: -1px;
        padding: 0; /* support: IE7 */
        height: 1.7em;
        top: 0.1em;
    }
    .custom-combobox-input
    {
        margin: 0;
        padding: 0.3em;
    }
    .style1
    {
        width: 225px;
    }
    .style2
    {
        width: 111px;
    }
</style>

<script type="text/javascript">

    $(document).ready(function () {

        $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });
        $("#btnClose").button({ icons: { primary: "ui-icon-close"} });

        $('#btnClose').click(function () {
            parent.$('#dialog').dialog("close");

            return false;
        });

    });

</script>

<script type="text/javascript" language="javascript">

    (function ($) {

        $.widget("custom.combobox", {
            _create: function () {
                this.wrapper = $("<span>")
          .addClass("custom-combobox")
          .insertAfter(this.element);

                this.element.hide();
                this._createAutocomplete();
                this._createShowAllButton();
            },

            _createAutocomplete: function () {
                var selected = this.element.children(":selected"),
          value = selected.val() ? selected.text() : "";

                var width = this.element.width() > 100 ? "style='width:" + this.element.width() + "px';" : "";

                this.input = $("<input " + width + ">")
          .appendTo(this.wrapper)
          .val(value)
          .attr("title", "")
          .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
          .autocomplete({
              autoFocus: true,
              selectFirst: true,
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
          })
          .tooltip({
              tooltipClass: "ui-state-highlight"
          });

                this._on(this.input, {
                    autocompleteselect: function (event, ui) {
                        ui.item.option.selected = true;
                        this._trigger("select", event, {
                            item: ui.item.option
                        });

                        var idOfCaller = this.element.attr('id');
                        switch (idOfCaller.toLowerCase()) {
                            case ("ddlnoinvoice"):
                                $('#ddlNoInvoice').change();
                                break;
                            case ("ddlbank"):
                                $('#ddlBank').change();
                                break;
                            default:
                                break;
                        }

                    },

                    autocompletechange: "_removeIfInvalid"
                });
            },

            _createShowAllButton: function () {
                var input = this.input,
          wasOpen = false;

                $("<a>")
          .attr("tabIndex", -1)
          .attr("title", "Tamplikan Semua Item")
          .tooltip()
          .appendTo(this.wrapper)
          .button({
              icons: {
                  primary: "ui-icon-triangle-1-s"
              },
              text: false
          })
          .removeClass("ui-corner-all")
          .addClass("custom-combobox-toggle ui-corner-right")
          .mousedown(function () {
              wasOpen = input.autocomplete("widget").is(":visible");
          })
          .click(function () {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                  return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
          });
            },

            _source: function (request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response(this.element.children("option").map(function () {
                    var text = $(this).text();
                    if (this.value && (!request.term || matcher.test(text)))
                        return {
                            label: text,
                            value: text,
                            option: this
                        };
                }));
            },

            _removeIfInvalid: function (event, ui) {

                // Selected an item, nothing to do
                if (ui.item) {
                    return;
                }

                // Search for a match (case-insensitive)
                var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
                this.element.children("option").each(function () {
                    if ($(this).text().toLowerCase() === valueLowerCase) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                // Found a match, nothing to do
                if (valid) {
                    return;
                }

                // Remove invalid value
                this.input
          .val("")
          .attr("title", value + " tidak ditemukan")
          .tooltip("open");
                this.element.val("");
                this._delay(function () {
                    this.input.tooltip("close").attr("title", "");
                }, 2500);
                this.input.data("ui-autocomplete").term = "";
            },

            _destroy: function () {
                this.wrapper.remove();
                this.element.show();
            },
            autocomplete: function (value, text) {
                this.element.val(value);
                this.input.val(text);
            }
        });
    })(jQuery);

    $(function () {

        $("#ddlBank").combobox();
        $("#ddlNoInvoice").combobox();
    });

</script>

<script type="text/javascript">

    $(document).ready(function () {

        // 1. prepare the validation rules and messages.
        var rules = {
           // txtDebitur: "required",
            txtJumlahPembayaran: "required",
            txtTanggalPembayaran: "required"

        };

        var messages = {
           // txtDebitur: "Nama Perusahaan harus di isi",
            txtJumlahPembayaran: "Jumlah Pembayaran harus di isi",
            txtTanggalPembayaran: "Tgl Pembayaran  harus di isi"
        };

        // 2. Initiate the validator
        var validator = new jQueryValidatorWrapper("form1", rules, messages);

        $("#txtJumlahPembayaran").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });

        var id = $('#<%= hfID.ClientID %>').val();
        if (id == "") {
            getBankAccount();
            $("#ddlNoInvoice").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", false).prop("disabled", false);
            $("#ddlBank").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", false).prop("disabled", false);
        }
        else {
            $("#ddlNoInvoice").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", true).prop("disabled", true);
            $("#ddlBank").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", true).prop("disabled", true);
        }

//        $("#txtTanggalPembayaran").datepicker({ showWeek: true, showButtonPanel: true,
//            changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy'//, yearRange: '2010:2030'
//        });


        var date = new Date();
        var currentMonth = date.getMonth();
        var currentDate = date.getDate();
        var currentYear = date.getFullYear();

        $("#txtTanggalPembayaran").datepicker({ showWeek: true, showButtonPanel: true,
            changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy', // yearRange: '1990:2030'
            maxDate: new Date(currentYear, currentMonth, currentDate)
        });



        $('#ddlNoInvoice').change(function () {
            getJumlahInvoice($(this).val());

            getRegistrasiID($(this).val());

          
        });


        $('#ddlBank').change(function () {
            getInvoiceNo();
        });

        // 3. Set the click event to do the validation
        $("#btnSave").click(function () {

            if (!validator.validate())
                return;

//            var d = new Date();
//            var month = d.getMonth() + 1;
//            var day = d.getDate();
//            var year = d.getFullYear();

//            var dateNow = day + "/" + month + "/" + year;
//            var tglSekarang = new Date(dateNow);
//            var valuedate = $("#txtTanggalPembayaran").val();
//            var tglInput = new Date(valuedate);

//            if (tglInput.getTime() > tglSekarang.getTime()) {
//                alert("Tgl. Pembayaran tidak boleh lebih besar dari Tgl. sekarang : " + dateNow);
//                return false;
//            }

            var InvoiceNo = $("#ddlNoInvoice option:selected").val();
            var JumlahPembayaran = $('#txtJumlahPembayaran').val();
            var TglPembayaran = $('#txtTanggalPembayaran').val();
            var DebtorSectorID = $('#hfDebtorSectorID').val();
            var Remark = $('#txtDebitur').val();
            var id = $('#hfID').val();

            var objrecPayment = new Object();
            objrecPayment.PaymentID = id;
            objrecPayment.PaymentValue = encodeURIComponent(JumlahPembayaran);
            objrecPayment.InvoiceNo = encodeURIComponent(InvoiceNo);
            objrecPayment.DebtorSectorID = encodeURIComponent(DebtorSectorID);
            objrecPayment.PaymentDate = encodeURIComponent(TglPembayaran);
            objrecPayment.Remark = encodeURIComponent(Remark);
            
            jsonData = JSON.stringify(objrecPayment);

            var handlerUrl = '<%= ResolveUrl("~/ajaxhandler/Transaction/recPaymenthandler.ashx") %>';

            if (id == 0)
                CallAjax(handlerUrl, "?method=insert", jsonData);
            else {
                CallAjax(handlerUrl, "?method=update", jsonData);
            }

            parent.$('#dialog').dialog('close');

            setTimeout("parent.$('#table').trigger('reloadGrid');", 3000);

            return false;
        });


    });

    function getJumlahInvoice(invoiceno) {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getinvoice.ashx?method=getbyinvoiceno") %>';
        
        $("#txtJumlahPembayaran").val('');
        $("#txtDebitur").val('');

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&invoiceno=" + invoiceno,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {

                $.each(datas, function (i, data) {

                    var money = parseFloat(data.InvoiceValue);

                    $("#txtJumlahPembayaran").val(money.formatMoney(2, ".", ","));
                    $('#hfDebtorSectorID').val(data.DebtorSectorID);

                    getDebtorID(data.DebtorSectorID);

                });

            },
            error: function () {
                alert('Error load jumlah pembayaran invoice !');
            }
        });

    }

    function getDebtorID(debtorsectorID) {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getdebtorsector.ashx?method=getbyid") %>';

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&debtorsectorID=" + debtorsectorID,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {

                $.each(datas, function (i, data) {
                    getNameDebtor(data.DebtorID);
                });

            },
            error: function () {
                alert('Error load Debtor ID !');
            }
        });

    }

    function getNameDebtor(debtorID) {
    
        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getdebtor.ashx?method=getbyid") %>';

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&debtorID=" + debtorID,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {
                
                $.each(datas, function (i, data) {
                    $("#txtDebitur").val(data.DebtorName);
                });

            },
            error: function () {
                alert('Error load nama perusahaan !');
            }
        });

    }

    function getBankAccount() {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getbankaccount.ashx") %>';
       
        $ddlBank = $('#ddlBank');
        $('#ddlBank').find('option:not(:first)').remove();

        $.ajax({
            type: 'POST',
            url: handlerUrl,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {

                if (datas.length > 1) {

                    $ddlBank.get(0).options[0] = new Option("-- pilih bank --", "");
                    $.each(datas, function (i, data) {
                        $ddlBank.append('<option value="' + data.BankID + '">' + data.BankCode + ' - ' + data.BankName + '</option>');
                    });
                    $ddlBank.combobox('autocomplete', "", "-- pilih bank --");
                }
                else {
                    if (datas.length == 1) {
                        $ddlBank.append('<option value="' + datas[0].BankID + '">' + datas[0].BankCode + ' - ' + datas[0].BankName + '</option>');
                        $ddlBank.combobox('autocomplete', datas[0].BankID, datas[0].BankCode + ' - ' + datas[0].BankName);

                        getInvoiceNo();
                    }
                    else {
                        $ddlBank.get(0).options[0] = new Option("-- tidak ada data --", "");
                        $ddlBank.combobox('autocomplete', "", "-- tidak ada data --");
                    }
                }
            },
            error: function () {
                alert('Error load data bank !');
            }
        });

    }

    function getInvoiceNo() {

        $("#txtJumlahPembayaran").val('');

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getinvoice.ashx?method=getbybankid") %>';
        var bankid = $("#ddlBank option:selected").val();

        $ddlInvoice = $('#ddlNoInvoice');
        $('#ddlNoInvoice').find('option:not(:first)').remove();

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&bankid=" + bankid,
            contentType: 'application/json',
            dataType: 'json',
            success: function (datas) {

                if (datas.length > 1) {
                    $ddlInvoice.get(0).options[0] = new Option("-- pilih surat setoran --", "");
                    $.each(datas, function (i, data) {
                        $ddlInvoice.append('<option value="' + data.InvoiceNo + '">' + data.InvoiceNo + '</option>');
                    });
                    $ddlInvoice.combobox('autocomplete', "", "-- pilih surat setoran --");
                }
                else {

                    if (datas.length == 1) {
                        $ddlInvoice.append('<option value="' + datas[0].InvoiceNo + '">' + datas[0].InvoiceNo + '</option>');
                        $ddlInvoice.combobox('autocomplete', datas[0].InvoiceNo, datas[0].InvoiceNo);

                         getJumlahInvoice(datas[0].InvoiceNo);
                        getRegistrasiID(datas[0].InvoiceNo);
                    }
                    else {
                        $ddlInvoice.get(0).options[0] = new Option("-- tidak ada data --", "");
                        $ddlInvoice.combobox('autocomplete', "", "-- tidak ada data --");
                    }

                }
            },
            error: function () {
                alert('Error load data bank !');
            }
        });

    }

    function getRegistrasiID(InvoiceNo) {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getrecSectorRegistration.ashx?method=GetByInvoiceNo") %>';

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&InvoiceNo=" + InvoiceNo,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                if (data.RegistrationID != "0") {
                    getRegistrasiName(data.RegistrationID);
                }
                else {
                    getAksiName(InvoiceNo);
                }
            },
            error: function () {
                alert('Error load registrasi ID !');
            }
        });

    }

    function getRegistrasiName(RegistrationID) {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getrecRegistration.ashx?method=GetByID") %>';

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&RegistrationID=" + RegistrationID,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                $("#txtDebitur").val(data.RegistrationName);
            },
            error: function () {
                alert('Error load registrasi Name !');
            }
        });

    }

    function getAksiName(InvoiceNo) {

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getrecCorporateAction.ashx?method=GetByInvoiceNo") %>';

        $.ajax({
            type: 'POST',
            url: handlerUrl + "&InvoiceNo=" + InvoiceNo,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                $("#txtDebitur").val(data.CorporateName);
            },
            error: function () {
                alert('Error load aksi Name !');
            }
        });

    }

</script>

<body>
    <form id="form1" runat="server">
    <table border="0">
        <tr>
            <td style="width: 50">
                Bank
            </td>
            <td>
                :
            </td>
            <td>
                <asp:DropDownList ID="ddlBank" runat="server" Width="300">
                </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: Red;">*</span>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td style="width: 50">
                No. Surat Setoran
            </td>
            <td>
                :
            </td>
            <td>
                 <asp:DropDownList ID="ddlNoInvoice" runat="server" Width="300">
                </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: Red;">*</span>
            </td>
        </tr>

        <tr>
            <td style="width: 50">
                Perusahaan
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtDebitur" runat="server" Width="300" Enabled="false"  ></asp:TextBox>
            </td>
        </tr>
        
        <tr>
            <td style="width: 50">
                Jumlah Pembayaran
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtJumlahPembayaran" runat="server" style="text-align:right" Width="200" MaxLength="100"></asp:TextBox>&nbsp;<span style="color: Red;">*</span>
            </td>
        </tr>

        <tr>
            <td style="width: 50">
                Tgl. Pembayaran
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtTanggalPembayaran" runat="server" Width="100" MaxLength="10"></asp:TextBox>&nbsp;<span style="color: Red;">*</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;
            </td>
            <td>
                <asp:HiddenField ID="hfID" runat="server" />
                <asp:HiddenField ID="hfDebtorSectorID" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;
            </td>
            <td>
                <div style="text-align: right; padding-top: 10px;">
                    <button id="btnSave" type="button">
                        Simpan</button>
                    <button id="btnClose" type="button">
                        Batal</button>
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
